package com.utilities.IO.fileWriters;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class XLSfileWriter {
	
	private ArrayList<String> columNames = null; 
	private ArrayList<String> rows = null;
	private String fileName = null;

	public XLSfileWriter(XLSFileWriterBuilder xLSFileWriterBuilder) {
		columNames = xLSFileWriterBuilder.columNames;
		rows = xLSFileWriterBuilder.rows;
		fileName = xLSFileWriterBuilder.fileName;
	}
	
	public boolean write()
	{
		try {
			FileOutputStream fs = new FileOutputStream(fileName);
		    HSSFWorkbook wb = new HSSFWorkbook();
		    HSSFSheet sheet = wb.createSheet();
		    HSSFRow row = sheet.createRow(0);
		    HSSFCell cell;
		    
		    HSSFCellStyle cs1 = wb.createCellStyle( );
		    HSSFFont f1 = wb.createFont( );
		    f1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		    f1.setFontHeightInPoints((short)10);
		    cs1.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		    cs1.setFont(f1);

		    int index = 0;
		    for (String columnName : columNames)
		    {
		    	cell = row.createCell(index);
		    	cell.setCellStyle(cs1);
		    	cell.setCellValue(columnName); 
		    	index++;
		    }
		    index = 1;
		    for (String rowData : rows)
		    {
		    	String[] data = rowData.split(",");
		    	row = sheet.createRow(index);
		    	int columnIndex = 0;
		    	for(String columnData : data)
		    	{
		    		cell = row.createCell(columnIndex);
		    		if (cell != null)
		    		{
		    			cell.setCellValue(columnData);
		    			columnIndex++;
		    		}
		    	}
		    	index++;
		    }
		    wb.write(fs);
		    fs.flush();
		    fs.close();
		} 
		catch(Exception ioe) 
		{
		    ioe.printStackTrace();
		    return false;
		}
		return true;
	}

	public static class XLSFileWriterBuilder
	{
		private ArrayList<String> columNames = null;
		private ArrayList<String> rows = null;
		private String fileName = null;
		
		public XLSFileWriterBuilder(String fileName)
		{
			this.fileName = fileName;
		}
		
		public void addColumn(String columnName)
		{
			columNames.add(columnName);
		}
		
		public void addColumns(String[] columns)
		{
			columNames.addAll(Arrays.asList(columns));
		}
		
		public void addRow(String row)
		{
			rows.add(row);
		}
		
		public void addRows(String[] row)
		{
			rows.addAll(Arrays.asList(row));
		}
		
		public XLSfileWriter build()
		{
			return new XLSfileWriter(this);
		}
	}
}